<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .signal-light {
      width: 400px;
      margin: 100px auto;
    }

    .light {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
      width: 120px;
      height: 360px;
      padding: 10px;
      background-color: #333;
      border-radius: 100px;
    }

    .light div {
      width: 100px;
      height: 100px;
      background-color: #eee;
      border-radius: 50%;
    }

    .countdown {
      width: 120px;
      height: 120px;
      margin-top: 20px;
      margin-left: 10px;
      text-align: center;
      line-height: 120px;
      font-size: 32px;
      color: #333;
      background-color: #eee;
      border-radius: 50%;
    }

    #red.active {
      background-color: red;
    }

    #yellow.active {
      background-color: yellow;
    }

    #green.active {
      background-color: green;
    }
  </style>
</head>

<body>
  <div class="signal-light">
    <div class="light">
      <div id="red"></div>
      <div id="yellow"></div>
      <div id="green"></div>
    </div>
    <div class="countdown" id="countdown">2</div>
  </div>
  <script>
    //  红绿灯倒计时
    function SignalLight(ele, timeout, nextLight) {
      this.ele = ele;
      this.timeout = timeout;
      this.nextLight = nextLight;
    }
    //获取id
    function getId(id) {
      return document.getElementById(id);
    }
    SignalLight.prototype.clearColor = function () {
      this.ele.className = '';
    }
    SignalLight.prototype.changeColor = function () {
      this.ele.className = 'active';
    }
    SignalLight.prototype.changeNum = function (num) {
      getId('countdown').innerHTML = num < 10 ? '0' + num : num;
    }

    var red = new SignalLight(getId('red'), 30, 'green');
    var yellow = new SignalLight(getId('yellow'), 5, 'red');
    var green = new SignalLight(getId('green'), 30, 'yellow');

    var nowLight = green;
    var timeout = nowLight.timeout;
    nowLight.changeColor();
    nowLight.changeNum(timeout);
    setInterval(function () {
      --timeout;
      if (timeout <= 0) {
        nowLight.clearColor();
        nowLight = window[nowLight.nextLight];
        timeout = nowLight.timeout;
        nowLight.changeColor();
      }
      nowLight.changeNum(timeout);
    }, 1000);
  </script>
</body>

</html>